package com.hmy.gateway.config;

import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;

import java.io.IOException;
import java.rmi.ServerException;

@Slf4j
public class KeepUaaErrMsgConfig {

    @Bean
    public ErrorDecoder errorDecoder() {
        return new ExceptionErrorDecoder();
    }

    public static class ExceptionErrorDecoder implements ErrorDecoder {
        @Override
        public Exception decode(String s, Response response) {
            String body = null;
            try {
                body = Util.toString(response.body().asReader());
            } catch (IOException e) {
                log.warn("feign解析异常获取body出错");
            }
            int status = response.status();
            if (HttpStatus.FORBIDDEN.value() == status || HttpStatus.UNAUTHORIZED.value() == status) {
                return new HttpClientErrorException(HttpStatus.FORBIDDEN, body);
            }
            return new ServerException("服务器内部错误");
        }
    }

}
